package top.likeqc.moneymark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import top.likeqc.moneymark.entity.Account;
import top.likeqc.moneymark.entity.Bill;
import top.likeqc.moneymark.mapper.AccountMapper;
import top.likeqc.moneymark.mapper.BillMapper;
import top.likeqc.moneymark.service.AccountService;
import top.likeqc.moneymark.util.ShiroUtil;

import java.math.BigDecimal;

/**
 * 服务实现类
 *
 * @author likeqc.top
 * @since 2021-07-03
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account>
        implements AccountService {

    // @Autowired BillService billService;
    // @Autowired AccountService accountService;
    @Autowired AccountMapper accountMapper;
    @Autowired BillMapper billMapper;

    @Override
    @Transactional
    public void deleteById(Integer id, Integer newId) {

        Integer userid = ShiroUtil.getProfile().getId();
        // Account account = accountService.getById(id);
        Account account = accountMapper.selectById(id);
        Assert.isTrue(userid.equals(account.getUserId()), "您不是该资产账户的拥有者");

        // 删除资产账户 x，需要提前修改使用要 x 资产账户的账单
        if (newId != null) {
            account = accountMapper.selectById(newId);
            Assert.isTrue(userid.equals(account.getUserId()), "您不是新的目标资产账户的拥有者");
        } else {
            // 使用默认账户
            Account defaultAccount =
                    accountMapper.selectOne(
                            new QueryWrapper<Account>().eq("user_id", userid).eq("name", "默认账户"));
            if (defaultAccount == null) {
                defaultAccount = new Account();
                defaultAccount.setUserId(userid);
                defaultAccount.setName("默认账户");
                defaultAccount.setMoney(new BigDecimal(0));
                // accountService.save(defaultAccount);
                accountMapper.insert(defaultAccount);
            }
            newId = defaultAccount.getId();
        }
        // 更新 bill 中使用到了待删除的资产账户的记录
        UpdateWrapper<Bill> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userid);
        updateWrapper.eq("account_id", id);
        updateWrapper.set("account_id", newId);
        // billService.update(null, updateWrapper);
        billMapper.update(null, updateWrapper);
        // int i = 1 / 0;
        // 删除资产账户
        // accountService.removeById(id);
        accountMapper.deleteById(id);
    }
}
